import sys
import re
import time

from PyQt5.QtWidgets import *
from untitled import Ui_MainWindow
from PyQt5.QtCore import Qt, QThread
import ProceDataLayer as PDL
import os
from commonData import ComData as cd


class MyMainForm(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(MyMainForm, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle(cd.title + cd.version)
        self.button_choice.clicked.connect(self.get_txt_folders)
        self.line_file.editingFinished.connect(self.get_txt_folders_by_ef) # 以编辑结束的形式获得输入文件夹
        self.button_choice_put.clicked.connect(self.get_out_folders)
        self.line_out_folder.editingFinished.connect(self.get_out_folders_by_ef)  # 以编辑结束的形式获取输出文件夹
        self.button_star.clicked.connect(self.star)
        self.button_end.clicked.connect(self.end)
        self.tree_fields.itemChanged.connect(self.onclick)

        """处理框槽函数"""
        self.public_check_box.stateChanged.connect(self.set_user_assign_state)
        self.comboBox_dist_num.currentIndexChanged.connect(self.set_dist_num)
        self.comboBox_province.currentIndexChanged.connect(self.set_province)
        self.comboBox_site_num.currentIndexChanged.connect(self.set_site_num)
        self.comboBox_long.currentIndexChanged.connect(self.set_long)
        self.comboBox_lat.currentIndexChanged.connect(self.set_lat)
        self.comboBox_alt.currentIndexChanged.connect(self.set_alt)
        self.btn_user_assign_excel.clicked.connect(self.get_assign_excel)
        self.text_public_floder.editingFinished.connect(self.get_assign_excel_by_ef) # 直接复制进去

        # """用户指定excel提取指定站点的槽函数"""
        # self.button_choice_excel_folder.clicked.connect(self.get_excel_folder)   # 指定的文件夹
        # self.button_choice_user_excel_file.clicked.connect(self.get_user_excel_file)  # 指定的excel文件
        # self.check_box_excel.stateChanged.connect(self.set_user_excel_state)
        # self.button_choice_put_excel.clicked.connect(self.get_excel_out_folder)

    # def get_excel_out_folder(self):
    #     fileName = QFileDialog.getExistingDirectory(self, directory="C:").replace('/', "\\")
    #     if fileName != "":
    #         self.line_out_excel_folder.setText(fileName)
    #         cd.folder_excel_out = fileName
    #
    #
    # def set_user_excel_state(self):  # 是否为用户处理指定的excel文件
    #     if self.check_box_excel.isChecked():
    #         cd.user_excel_state = True
    #     else:
    #         cd.user_excel_state = False
    #
    #
    # def get_excel_folder(self):  # 获取用户指定的excel文件所在的文件夹
    #     fileName = QFileDialog.getExistingDirectory(self, directory="C:").replace('/', "\\")
    #     if fileName != "":
    #         self.check_box_excel.setCheckState(Qt.Checked)  # 若是选中了文件，则表示要处理该数据
    #         cd.user_excel_state = True
    #         self.line_file_excel_folder.setText(fileName)
    #         cd.user_excel_folder = fileName
    #         if cd.folder_excel_out == "":  # 如果是空的
    #             name = fileName[:2] + "\\根据excel提取站点输出文件夹"
    #             if not os.path.exists(name):
    #                 os.mkdir(name)
    #             self.line_out_excel_folder.setText(name)
    #             cd.folder_excel_out = name
    #
    # def get_user_excel_file(self):
    #     fileName = QFileDialog.getOpenFileName(self, directory="C:", filter="*.xlsx")[0].replace("/", "\\")
    #     if fileName != "":
    #         self.line_user_excel_file.setText(fileName)
    #         cd.user_excel_file = fileName


    def get_assign_excel(self):
        fileName = QFileDialog.getOpenFileName(self, directory="C:", filter="*.xlsx")[0].replace("/", "\\")
        if fileName != "":
            self.text_public_floder.setText(fileName)
            cd.assign_excel = fileName

    def get_assign_excel_by_ef(self):
        fileName = self.text_public_floder.text()
        if fileName != "":
            cd.assign_excel = fileName
        print(fileName)

    def set_dist_num(self):
        cd.dist_num_index = self.comboBox_dist_num.currentText()

    def set_province(self):
        cd.province_index = self.comboBox_province.currentText()

    def set_site_num(self):
        cd.site_name_index = self.comboBox_site_num.currentText()

    def set_long(self):
        cd.long_index = self.comboBox_long.currentText()

    def set_lat(self):
        cd.lat_index = self.comboBox_lat.currentText()

    def set_alt(self):
        cd.alt_index = self.comboBox_alt.currentText()

    def set_user_assign_state(self):
        if self.public_check_box.isChecked():  # 若是选中的
            cd.assign_state = True
        else:
            cd.assign_state = False


    def get_txt_folders_by_ef(self):
        fileName = self.line_file.text()
        if fileName != "":
            MyMainForm.set_file_in_tree(self, fileName)

    def get_out_folders_by_ef(self):
        fileName = self.line_out_folder.text()
        if fileName != "":
            cd.folder_out = fileName

    def onclick(self, item, state):
        info = item.text(0)
        if item.checkState(state) == Qt.Checked:
            if info not in cd.elements:
                cd.elements.append(info)
        else:  # 未选中
            if info in cd.elements:
                cd.elements.remove(info)


    def set_file_in_tree(self, fileName):
        self.tree_fields.clear()
        cd.elements = []
        if os.path.exists(fileName) == False:
            msg_box = QMessageBox(QMessageBox.Warning, '输入错误', '文件夹不存在，请重新输入!')
            msg_box.exec_()
        else:
            if len(os.listdir(fileName)) != 0:
                file = fileName + "\\" + os.listdir(fileName)[0]
                if 'xlsx' not in file and 'DAY' in file:
                    cd.DAY = True
                    cd.MONTH = False
                    cd.user_excel_state = False
                    suffix = '提取出的数据文件夹'
                elif 'xlsx' not in file and 'MONTH' in file:
                    cd.MONTH = True
                    cd.DAY = False
                    cd.user_excel_state = False
                    suffix = '提取出的数据文件夹'
                elif 'xlsx' in file:   # 若 为excel数据
                    cd.user_excel_state = True
                    self.line_file.setText(fileName)
                    cd.folder_in = fileName
                    cd.MONTH = cd.DAY = False
                    suffix = '根据excel提取站点输出文件夹'
                else:
                    msg_box = QMessageBox(QMessageBox.Warning, '输入错误', '输入文件夹内好像有错误，请检查')
                    msg_box.exec_()

                if cd.DAY or cd.MONTH:
                    self.line_file.setText(fileName)
                    cd.folder_in = fileName
                    f = open(file, 'r', encoding='utf-8')
                    firstLine = f.readline()
                    try:
                        elem = re.findall(r'elements=(.*)&', firstLine)[0].split(',')  # 给共同数据内的elements元素赋值
                    except Exception as e:
                        print("读取 txt 文件出错，可能是该文件不符合格式要求，请检查。\n异常信息:", e)
                    else:
                        if cd.DAY == True:
                            for e in elem[8:]:
                                root = QTreeWidgetItem(self.tree_fields)
                                root.setText(0, e)
                                root.setCheckState(0, Qt.Checked)
                        else:
                            for e in elem[7:]:
                                root = QTreeWidgetItem(self.tree_fields)
                                root.setText(0, e)
                                root.setCheckState(0, Qt.Checked)

                cd.folder_out = fileName[:2] + "\\" + suffix  # 默认放在输入文件夹对应的盘符
                self.line_out_folder.setText(cd.folder_out)
            else:
                msg_box = QMessageBox(QMessageBox.Warning, '输入错误', '输入文件夹内好像有错误，请查看是否为空文件夹')
                msg_box.exec_()
                os.startfile(fileName)  # 提示错误信息后，打开该文件夹

    def get_txt_folders(self):
        fileName = QFileDialog.getExistingDirectory(self, directory="C:").replace("/", "\\")
        if fileName != "":
                MyMainForm.set_file_in_tree(self, fileName)

    def get_out_folders(self):
        fileName = QFileDialog.getExistingDirectory(self, directory="C:").replace("/", "\\")  # 获取气温or降水所在的文件夹的位置
        if fileName != '':
            self.line_out_folder.setText(fileName)
            cd.folder_out = fileName

    def star(self):
        if not cd.user_excel_state:
            file = cd.folder_in + "\\" + os.listdir(cd.folder_in)[0]
            if 'DAY' in file:
                cd.DAY = True
                cd.MONTH = False
            else:
                cd.MONTH = True
                cd.DAY = False

            if os.path.exists(cd.folder_out) == False:
                os.mkdir(cd.folder_out)

        if cd.assign_state and cd.assign_excel == "":
            msg_box = QMessageBox(QMessageBox.Warning, "站点文件错误", "可能是你指定了要处理指定站点，却没有选择任何文件!")
            msg_box.exec_()
        else:
            self.thread = MyThread()
            self.thread.start()  # start调用的是run

    def end(self):
        sys.exit(app.exec_())


class MyThread(QThread):

    def __init__(self):
        super(MyThread, self).__init__()

    def run(self):
        startTime = time.time()
        # try:
        if cd.user_excel_state:
            PDL.Data().starExcel()
        else:
            if cd.DAY:
                PDL.Data().starDay()
            else:
                PDL.Data().starMonth()
        # except Exception as e:
        #     print("出现异常: ", e)
        print("处理完毕, 用时%.2f秒,%.2f分钟" % (time.time() - startTime, (time.time() - startTime) / 60))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWin = MyMainForm()
    myWin.show()
    sys.exit(app.exec_())
